import * as fs from "fs-extra";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { ValidationPipe } from "@nestjs/common";
import { envConfig } from "./config";
import { setupSwagger } from "./swagger";
import { ConfigService } from "@nestjs/config";

global.is = function is<T>(data: any, test: (data: any) => boolean): data is T {
    return test(data);
}


const httpsOptions = {
    key: fs.readFileSync("secrets/private-key.pem"),
    cert: fs.readFileSync("secrets/public-certificate.pem"),
};

async function bootstrap() {
    const https = envConfig["HTTPS"] == "true";
    const app = await NestFactory.create(AppModule, {
        cors: true,
        httpsOptions: https ? httpsOptions : null,
    });

    app.setGlobalPrefix("api", {
        exclude: ["file/get/:filename"],
    });


    app.useGlobalPipes(
        new ValidationPipe({
            transform: true,
            whitelist: true,
            transformOptions: { enableImplicitConversion: true },
            stopAtFirstError: true,
        }),
    );

    setupSwagger(app, app.get(ConfigService));

    // todo! 不知道为啥开启https之后 socket 连不上了
    await app.listen(parseInt(https ? envConfig["HTTPS_PROT"] : envConfig["HTTP_PROT"]));
}
bootstrap();
